﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;

namespace WorkOrder.Business
{
    public class DbHelper
    {
        #region 数据成员

        private static readonly string ConnectionString =
            ConfigurationManager.ConnectionStrings["WODBConnectionString"].ConnectionString;

        private static SqlConnection conn;
        private static SqlCommand cmd;

        #endregion

        public DbHelper()
        {
            conn = new SqlConnection(ConnectionString);
        }

        #region 打开数据库连接

        public static void OpenDbConnection()
        {
            if (conn.State != ConnectionState.Open)
                try
                {
                    conn.Open();
                }
                catch
                {
                }
        }

        #endregion

        #region 关闭数据库连接

        public void CloseDbConnection()
        {
            if (conn.State != ConnectionState.Closed)
                try
                {
                    conn.Close();
                }
                catch
                {
                }
        }

        public static void CloseDbConnection(SqlCommand cmmd)
        {
            if (cmmd.Connection != null)
            {
                try
                {
                    cmmd.Connection.Close();
                }
                catch
                {
                }
            }
            {
                try
                {
                    cmmd.Dispose();
                }
                catch
                {
                }
            }
        }

        #endregion

        #region 返回SqlDataReader

        public SqlDataReader Search(string sqlstr)
        {
            OpenDbConnection();
            if (cmd == null)
                cmd = new SqlCommand(sqlstr, conn);
            else
            {
                cmd.CommandText = sqlstr;
                cmd.Connection = conn;
            }
            return cmd.ExecuteReader();
            //finally { CloseDbConnection(cmd); }
        }

        #endregion

        #region 返回影响行数

        public int ExecuteNoQuery(string sqlstr)
        {
            OpenDbConnection();
            if (cmd == null)
                cmd = new SqlCommand(sqlstr, conn);
            else
            {
                cmd.CommandText = sqlstr;
                cmd.Connection = conn;
            }
            try
            {
                return cmd.ExecuteNonQuery();
            }
            finally
            {
                CloseDbConnection(cmd);
            }
        }

        /*
        public static int ExecuteNoQuery(string sqlstr, List<Parameter> ListParameters)
        {
            OpenDbConnection();
            if (cmd == null)
                cmd = new SqlCommand(sqlstr, conn);
            else
            {
                cmd.CommandText = sqlstr;
                cmd.Connection = conn;
            }
            try
            {
                PrepareCommand(cmd, null, ListParameters);
                return cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            { throw ex; }
            finally { CloseDbConnection(cmd); }
        }
        */

        #endregion

        #region 返回执行结果

        public int GetTotalCount(string SqlString)
        {
            object obj = ExecuteScalar(SqlString);
            if (obj == DBNull.Value)
                return 0;
            return Convert.ToInt32(obj);
        }

        public object ExecuteScalar(string sqlstr)
        {
            OpenDbConnection();
            if (cmd == null)
                cmd = new SqlCommand(sqlstr, conn);
            else
            {
                cmd.CommandText = sqlstr;
                cmd.Connection = conn;
            }
            try
            {
                return cmd.ExecuteScalar();
            }
            finally
            {
                CloseDbConnection(cmd);
            }
        }

        /*
        public static object ExecuteScalar(string sqlstr, List<Parameter> ListParameters)
        {
            OpenDbConnection();
            if (cmd == null)
                cmd = new SqlCommand(sqlstr, conn);
            else
            {
                cmd.CommandText = sqlstr;
                cmd.Connection = conn;
            }
            try
            {
                PrepareCommand(cmd, null, ListParameters);
                return cmd.ExecuteScalar();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                CloseDbConnection(cmd);
            }
        }
        */

        #endregion

        #region 处理事务

        public void ExecuteTrans(List<string> ListSqlString)
        {
            OpenDbConnection();
            using (SqlTransaction trans = conn.BeginTransaction())
            {
                SqlCommand cmmd = conn.CreateCommand();
                cmmd.Transaction = trans;
                try
                {
                    foreach (string sql in ListSqlString)
                    {
                        cmmd.CommandText = sql;
                        cmmd.ExecuteNonQuery();
                    }
                    trans.Commit();
                }
                catch (Exception)
                {
                    trans.Rollback();
                    throw;
                }
                finally
                {
                    CloseDbConnection(cmmd);
                }
            }
        }

        public DataTable ExecuteTransRetrunTable(string tableName, List<string> ListSqlString)
        {
            OpenDbConnection();
            DataTable table = new DataTable();
            using (SqlTransaction trans = conn.BeginTransaction())
            {
                SqlCommand cmmd = conn.CreateCommand();
                cmmd.Transaction = trans;
                SqlDataAdapter da = new SqlDataAdapter(cmmd);

                try
                {
                    foreach (string sql in ListSqlString)
                    {
                        cmmd.CommandText = sql;
                        da.Fill(table);
                    }
                    trans.Commit();
                }
                catch (Exception)
                {
                    trans.Rollback();
                    throw;
                }
                finally
                {
                    CloseDbConnection(cmmd);
                }
            }
            return table;
        }

        public void ExecuteTrans(IDictionary<string, List<Parameter>> ListParameters)
        {
            OpenDbConnection();
            SqlTransaction trans;
            using (trans = conn.BeginTransaction())
            {
                SqlCommand cmmd = conn.CreateCommand();
                cmmd.Transaction = trans;
                try
                {
                    foreach (KeyValuePair<string, List<Parameter>> kvp in ListParameters)
                    {
                        cmmd.CommandText = kvp.Key;
                        PrepareCommand(cmmd, trans, kvp.Value);
                        cmmd.ExecuteNonQuery();
                    }
                    trans.Commit();
                }
                catch (Exception)
                {
                    trans.Rollback();
                    throw;
                }
                finally
                {
                    CloseDbConnection(cmmd);
                }
            }
        }

        public void ExecuteTrans(List<ListSql> listSql)
        {
            OpenDbConnection();
            SqlTransaction trans;
            using (trans = conn.BeginTransaction())
            {
                SqlCommand cmmd = conn.CreateCommand();
                cmmd.Transaction = trans;
                try
                {
                    foreach (ListSql obj in listSql)
                    {
                        cmmd.CommandText = obj.SqlString;
                        PrepareCommand(cmmd, trans, obj.ListParameter);
                        cmmd.ExecuteNonQuery();
                    }
                    trans.Commit();
                }
                catch (Exception)
                {
                    trans.Rollback();
                    throw;
                }
                finally
                {
                    CloseDbConnection(cmmd);
                }
            }
        }

        public object ExecuteTrans(string[] sqlstr)
        {
            OpenDbConnection();
            using (SqlTransaction trans = conn.BeginTransaction())
            {
                SqlCommand cmmd = conn.CreateCommand();
                cmmd.Transaction = trans;
                int m = -1;
                try
                {
                    for (int i = 0; i < sqlstr.Length; i++)
                    {
                        m = i;//如出错，m为出错的行
                        cmmd.CommandText = sqlstr[i];
                        cmmd.ExecuteNonQuery();
                    }
                    trans.Commit();
                    return 0;//执行成功，返回0
                }
                catch
                {
                    trans.Rollback();
                    return m;
                }
                finally
                {
                    CloseDbConnection(cmmd);
                }
            }
        }

        #endregion

        #region 查询

        public DataSet Query(string sqlstr)
        {
            OpenDbConnection();
            cmd = new SqlCommand(sqlstr, conn);
            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = cmd;
            DataSet ds = new DataSet();
            try
            {
                da.Fill(ds);
            }
            catch(Exception ex)
            {
                
            }
            finally
            {
                CloseDbConnection(cmd);
            }
            return ds;
        }

        public DataSet Query(string sqlstr, List<Parameter> ListParameters)
        {
            OpenDbConnection();
            SqlCommand cmmd = new SqlCommand(sqlstr, conn);
            SqlDataAdapter da = new SqlDataAdapter();
            DataSet ds = new DataSet();
            try
            {
                PrepareCommand(cmmd, null, ListParameters);
                da.SelectCommand = cmmd;
                da.Fill(ds);
            }
            finally
            {
                CloseDbConnection(cmmd);
            }
            return ds;
        }

        public DataSet Query(string sqlstr, int PageSize, int CurrPage, string TableName)
        {
            OpenDbConnection();
            SqlCommand cmmd = new SqlCommand(sqlstr, conn);
            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = cmmd;
            DataSet ds = new DataSet();
            try
            {
                da.Fill(ds, CurrPage*PageSize, PageSize, TableName);
            }
            finally
            {
                CloseDbConnection(cmmd);
            }
            return ds;
        }

        public DataSet Query(string sqlstr, List<Parameter> ListParameters, int PageSize, int CurrPage, string TableName)
        {
            OpenDbConnection();
            SqlCommand cmmd = new SqlCommand(sqlstr, conn);
            SqlDataAdapter da = new SqlDataAdapter();
            PrepareCommand(cmmd, null, ListParameters);
            da.SelectCommand = cmmd;
            DataSet ds = new DataSet();
            try
            {
                da.Fill(ds, CurrPage*PageSize, PageSize, TableName);
            }
            finally
            {
                CloseDbConnection(cmmd);
            }
            return ds;
        }

        #endregion

        public static void PrepareCommand(SqlCommand cmmd, SqlTransaction trans, List<Parameter> ListParameters)
        {
            if (trans != null)
                cmmd.Transaction = trans;
            foreach (Parameter obj in ListParameters)
            {
                SqlParameter parm = cmmd.CreateParameter();
                parm.ParameterName = obj.Name;
                parm.Value = obj.Value;
                cmmd.Parameters.Add(parm);
            }
        }

        internal DataTable Query(string tablename, string sqlstr)
        {
            OpenDbConnection();
            cmd = new SqlCommand(sqlstr, conn);
            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = cmd;
            DataTable table = new DataTable();
            try
            {
                da.Fill(table);
            }
            catch (Exception)
            {
                return null;
            }
            finally
            {
                CloseDbConnection(cmd);
            }
            return table;
        }

        #region 判断是否存在

        public bool Exists(string strSql)
        {
            object obj = GetSingle(strSql);
            int cmdresult;
            if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
            {
                cmdresult = 0;
            }
            else
            {
                cmdresult = int.Parse(obj.ToString());
            }
            if (cmdresult == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        public bool Exists(string strSql, params SqlParameter[] cmdParms)
        {
            object obj = GetSingle(strSql, cmdParms);
            int cmdresult;
            if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
            {
                cmdresult = 0;
            }
            else
            {
                cmdresult = int.Parse(obj.ToString());
            }
            if (cmdresult == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        #endregion

        #region  执行简单SQL语句

        /// <summary>
        /// 执行SQL语句，返回影响的记录数
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public int ExecuteSql(string SQLString)
        {
            try
            {
                OpenDbConnection();
                cmd = new SqlCommand(SQLString, conn);
                int rows = cmd.ExecuteNonQuery();
                return rows;
            }
            catch (System.Data.SqlClient.SqlException e)
            {
                throw e;
            }
            finally
            {
                CloseDbConnection(cmd);
            }
        }

        public int ExecuteSqlByTime(string SQLString, int Times)
        {
            try
            {
                OpenDbConnection();
                cmd = new SqlCommand(SQLString, conn);
                cmd.CommandTimeout = Times;
                int rows = cmd.ExecuteNonQuery();
                return rows;
            }
            catch (System.Data.SqlClient.SqlException e)
            {
                throw e;
            }
            finally
            {
                CloseDbConnection(cmd);
            }
        }

        /// <summary>
        /// 执行多条SQL语句，实现数据库事务。
        /// </summary>
        /// <param name="SQLStringList">多条SQL语句</param>		
        public int ExecuteSqlTran(List<String> SQLStringList)
        {
            OpenDbConnection();
            cmd = new SqlCommand();
            cmd.Connection = conn;
            SqlTransaction tx = conn.BeginTransaction();
            cmd.Transaction = tx;
            try
            {
                int count = 0;
                for (int n = 0; n < SQLStringList.Count; n++)
                {
                    string strsql = SQLStringList[n];
                    if (strsql.Trim().Length > 1)
                    {
                        cmd.CommandText = strsql;
                        count += cmd.ExecuteNonQuery();
                    }
                }
                tx.Commit();
                return count;
            }
            catch
            {
                tx.Rollback();
                return 0;
            }
            finally
            {
                CloseDbConnection(cmd);
            }
        }

        /// <summary>
        /// 执行带一个存储过程参数的的SQL语句。
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <param name="content">参数内容,比如一个字段是格式复杂的文章，有特殊符号，可以通过这个方式添加</param>
        /// <returns>影响的记录数</returns>
        public int ExecuteSql(string SQLString, string content)
        {
            cmd = new SqlCommand(SQLString, conn);
            SqlParameter myParameter = new SqlParameter("@content", SqlDbType.NText);
            OpenDbConnection();
            myParameter.Value = content;
            cmd.Parameters.Add(myParameter);
            try
            {
                int rows = cmd.ExecuteNonQuery();
                return rows;
            }
            catch (SqlException e)
            {
                throw e;
            }
            finally
            {
                CloseDbConnection(cmd);
                cmd.Dispose();
            }
        }


        /// <summary>
        /// 执行带一个存储过程参数的的SQL语句。
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <param name="content">参数内容,比如一个字段是格式复杂的文章，有特殊符号，可以通过这个方式添加</param>
        /// <returns>影响的记录数</returns>
        public object ExecuteSqlGet(string SQLString, string content)
        {
            OpenDbConnection();
            cmd = new SqlCommand(SQLString, conn);
            SqlParameter myParameter = new SqlParameter("@content",
                                                        SqlDbType.NText);
            myParameter.Value = content;
            cmd.Parameters.Add(myParameter);
            try
            {
                object obj = cmd.ExecuteScalar();
                if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                {
                    return null;
                }
                else
                {
                    return obj;
                }
            }
            catch (SqlException e)
            {
                throw e;
            }
            finally
            {
                CloseDbConnection(cmd);
                cmd.Dispose();
            }
        }


        /// <summary>
        /// 向数据库里插入图像格式的字段(和上面情况类似的另一种实例)
        /// </summary>
        /// <param name="strSQL">SQL语句</param>
        /// <param name="fs">图像字节,数据库的字段类型为image的情况</param>
        /// <returns>影响的记录数</returns>
        public int ExecuteSqlInsertImg(string strSQL, byte[] fs)
        {
            OpenDbConnection();
            cmd = new SqlCommand(strSQL, conn);
            SqlParameter myParameter = new SqlParameter("@fs",
                                                        SqlDbType.Image);
            myParameter.Value = fs;
            cmd.Parameters.Add(myParameter);
            try
            {
                int rows = cmd.ExecuteNonQuery();
                return rows;
            }
            catch (SqlException e)
            {
                throw e;
            }
            finally
            {
                CloseDbConnection(cmd);
                cmd.Dispose();
            }
        }


        /// <summary>
        /// 执行一条计算查询结果语句，返回查询结果（object）。
        /// </summary>
        /// <param name="SQLString">计算查询结果语句</param>
        /// <returns>查询结果（object）</returns>
        public object GetSingle(string SQLString)
        {
            OpenDbConnection();
            cmd = new SqlCommand(SQLString, conn);


            try
            {
                object obj = cmd.ExecuteScalar();
                if ((Object.Equals(obj, null)) || (Object.Equals(obj, DBNull.Value)))
                {
                    return null;
                }
                else
                {
                    return obj;
                }
            }
            catch (SqlException e)
            {
                throw e;
            }
            finally
            {
                CloseDbConnection(cmd);
            }
        }

        public static object GetSingle(string SQLString, int Times)
        {
            OpenDbConnection();

            cmd = new SqlCommand(SQLString, conn);

            try
            {
                cmd.CommandTimeout = Times;
                object obj = cmd.ExecuteScalar();
                if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                {
                    return null;
                }
                else
                {
                    return obj;
                }
            }
            catch (SqlException e)
            {
                throw e;
            }
            finally
            {
                CloseDbConnection(cmd);
            }
        }

        /// <summary>
        /// 执行查询语句，返回SqlDataReader ( 注意：调用该方法后，一定要对SqlDataReader进行Close )
        /// </summary>
        /// <param name="strSQL">查询语句</param>
        /// <returns>SqlDataReader</returns>
        public SqlDataReader ExecuteReader(string strSQL)
        {
            OpenDbConnection();
            cmd = new SqlCommand(strSQL, conn);
            try
            {
                SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                return myReader;
            }
            catch (SqlException e)
            {
                throw e;
            }
            finally
            {
                CloseDbConnection(cmd);
            }
        }


        public DataSet Query(string SQLString, int Times)
        {
            OpenDbConnection();
            DataSet ds = new DataSet();
            try
            {
                SqlDataAdapter da = new SqlDataAdapter(SQLString, conn);
                da.SelectCommand.CommandTimeout = Times;
                da.Fill(ds, "ds");
            }
            catch (SqlException ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                CloseDbConnection(cmd);
            }
            return ds;
        }

        #endregion

        #region 执行带参数的SQL语句

        /// <summary>
        /// 执行SQL语句，返回影响的记录数
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public int ExecuteSql(string SQLString, params SqlParameter[] cmdParms)
        {
            OpenDbConnection();
            cmd = new SqlCommand();
            try
            {
                PrepareCommand(cmd, conn, null, SQLString, cmdParms);
                int rows = cmd.ExecuteNonQuery();
                cmd.Parameters.Clear();
                return rows;
            }
            catch (SqlException e)
            {
                throw e;
            }
            finally
            {
                CloseDbConnection(cmd);
            }
        }


        /// <summary>
        /// 执行多条SQL语句，实现数据库事务。
        /// </summary>
        /// <param name="SQLStringList">SQL语句的哈希表（key为sql语句，value是该语句的SqlParameter[]）</param>
        public void ExecuteSqlTran(Hashtable SQLStringList)
        {
            OpenDbConnection();
            using (SqlTransaction trans = conn.BeginTransaction())
            {
                cmd = new SqlCommand();
                try
                {
                    //循环
                    foreach (DictionaryEntry myDE in SQLStringList)
                    {
                        string cmdText = myDE.Key.ToString();
                        SqlParameter[] cmdParms = (SqlParameter[]) myDE.Value;
                        PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
                        int val = cmd.ExecuteNonQuery();
                        cmd.Parameters.Clear();
                    }
                    trans.Commit();
                }
                catch
                {
                    trans.Rollback();
                    throw;
                }
                finally
                {
                    CloseDbConnection(cmd);
                }
            }
        }

        /// <summary>
        /// 执行多条SQL语句，实现数据库事务。
        /// </summary>
        /// <param name="SQLStringList">SQL语句的哈希表（key为sql语句，value是该语句的SqlParameter[]）</param>
        public int ExecuteSqlTran(System.Collections.Generic.List<CommandInfo> cmdList)
        {
            OpenDbConnection();

            using (SqlTransaction trans = conn.BeginTransaction())
            {
                cmd = new SqlCommand();
                try
                {
                    int count = 0;
                    //循环
                    foreach (CommandInfo myDE in cmdList)
                    {
                        string cmdText = myDE.CommandText;
                        SqlParameter[] cmdParms = (SqlParameter[]) myDE.Parameters;
                        PrepareCommand(cmd, conn, trans, cmdText, cmdParms);

                        if (myDE.EffentNextType == EffentNextType.WhenHaveContine ||
                            myDE.EffentNextType == EffentNextType.WhenNoHaveContine)
                        {
                            if (myDE.CommandText.ToLower().IndexOf("count(") == -1)
                            {
                                trans.Rollback();
                                return 0;
                            }

                            object obj = cmd.ExecuteScalar();
                            bool isHave = false;
                            if (obj == null && obj == DBNull.Value)
                            {
                                isHave = false;
                            }
                            isHave = Convert.ToInt32(obj) > 0;

                            if (myDE.EffentNextType == EffentNextType.WhenHaveContine && !isHave)
                            {
                                trans.Rollback();
                                return 0;
                            }
                            if (myDE.EffentNextType == EffentNextType.WhenNoHaveContine && isHave)
                            {
                                trans.Rollback();
                                return 0;
                            }
                            continue;
                        }
                        int val = cmd.ExecuteNonQuery();
                        count += val;
                        if (myDE.EffentNextType == EffentNextType.ExcuteEffectRows && val == 0)
                        {
                            trans.Rollback();
                            return 0;
                        }
                        cmd.Parameters.Clear();
                    }
                    trans.Commit();
                    return count;
                }
                catch
                {
                    trans.Rollback();
                    throw;
                }
                finally
                {
                    CloseDbConnection(cmd);
                }
            }
        }

        /// <summary>
        /// 执行多条SQL语句，实现数据库事务。
        /// </summary>
        /// <param name="SQLStringList">SQL语句的哈希表（key为sql语句，value是该语句的SqlParameter[]）</param>
        public void ExecuteSqlTranWithIndentity(System.Collections.Generic.List<CommandInfo> SQLStringList)
        {
            OpenDbConnection();
            using (SqlTransaction trans = conn.BeginTransaction())
            {
                cmd = new SqlCommand();
                try
                {
                    int indentity = 0;
                    //循环
                    foreach (CommandInfo myDE in SQLStringList)
                    {
                        string cmdText = myDE.CommandText;
                        SqlParameter[] cmdParms = (SqlParameter[]) myDE.Parameters;
                        foreach (SqlParameter q in cmdParms)
                        {
                            if (q.Direction == ParameterDirection.InputOutput)
                            {
                                q.Value = indentity;
                            }
                        }
                        PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
                        int val = cmd.ExecuteNonQuery();
                        foreach (SqlParameter q in cmdParms)
                        {
                            if (q.Direction == ParameterDirection.Output)
                            {
                                indentity = Convert.ToInt32(q.Value);
                            }
                        }
                        cmd.Parameters.Clear();
                    }
                    trans.Commit();
                }
                catch
                {
                    trans.Rollback();
                    throw;
                }
                finally
                {
                    CloseDbConnection(cmd);
                }
            }
        }

        /// <summary>
        /// 执行多条SQL语句，实现数据库事务。
        /// </summary>
        /// <param name="SQLStringList">SQL语句的哈希表（key为sql语句，value是该语句的SqlParameter[]）</param>
        public void ExecuteSqlTranWithIndentity(Hashtable SQLStringList)
        {
            OpenDbConnection();
            using (SqlTransaction trans = conn.BeginTransaction())
            {
                cmd = new SqlCommand();
                try
                {
                    int indentity = 0;
                    //循环
                    foreach (DictionaryEntry myDE in SQLStringList)
                    {
                        string cmdText = myDE.Key.ToString();
                        SqlParameter[] cmdParms = (SqlParameter[]) myDE.Value;
                        foreach (SqlParameter q in cmdParms)
                        {
                            if (q.Direction == ParameterDirection.InputOutput)
                            {
                                q.Value = indentity;
                            }
                        }
                        PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
                        int val = cmd.ExecuteNonQuery();
                        foreach (SqlParameter q in cmdParms)
                        {
                            if (q.Direction == ParameterDirection.Output)
                            {
                                indentity = Convert.ToInt32(q.Value);
                            }
                        }
                        cmd.Parameters.Clear();
                    }
                    trans.Commit();
                }
                catch
                {
                    trans.Rollback();
                    throw;
                }
                finally
                {
                    CloseDbConnection(cmd);
                }
            }
        }

        /// <summary>
        /// 执行一条计算查询结果语句，返回查询结果（object）。
        /// </summary>
        /// <param name="SQLString">计算查询结果语句</param>
        /// <returns>查询结果（object）</returns>
        public object GetSingle(string SQLString, params SqlParameter[] cmdParms)
        {
            OpenDbConnection();
            cmd = new SqlCommand();
            try
            {
                PrepareCommand(cmd, conn, null, SQLString, cmdParms);
                object obj = cmd.ExecuteScalar();
                cmd.Parameters.Clear();
                if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                {
                    return null;
                }
                else
                {
                    return obj;
                }
            }
            catch (System.Data.SqlClient.SqlException e)
            {
                throw e;
            }
            finally
            {
                CloseDbConnection(cmd);
            }
        }

        /// <summary>
        /// 执行查询语句，返回SqlDataReader ( 注意：调用该方法后，一定要对SqlDataReader进行Close )
        /// </summary>
        /// <param name="strSQL">查询语句</param>
        /// <returns>SqlDataReader</returns>
        public SqlDataReader ExecuteReader(string SQLString, params SqlParameter[] cmdParms)
        {
            OpenDbConnection();
            cmd = new SqlCommand();
            try
            {
                PrepareCommand(cmd, conn, null, SQLString, cmdParms);
                SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                cmd.Parameters.Clear();
                return myReader;
            }
            catch (SqlException e)
            {
                throw e;
            }
            finally
            {
                CloseDbConnection(cmd);
            }
        }

        /// <summary>
        /// 执行查询语句，返回DataSet
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// <returns>DataSet</returns>
        public DataSet Query(string SQLString, params SqlParameter[] cmdParms)
        {
            OpenDbConnection();
            cmd = new SqlCommand();
            PrepareCommand(cmd, conn, null, SQLString, cmdParms);
            using (SqlDataAdapter da = new SqlDataAdapter(cmd))
            {
                DataSet ds = new DataSet();
                try
                {
                    da.Fill(ds, "ds");
                    cmd.Parameters.Clear();
                }
                catch (SqlException ex)
                {
                    throw new Exception(ex.Message);
                }
                finally
                {
                    CloseDbConnection(cmd);
                }
                return ds;
            }
        }


        private static void PrepareCommand(SqlCommand cmmd, SqlConnection connetion, SqlTransaction trans,
                                           string cmdText,
                                           SqlParameter[] cmdParms)
        {
            if (connetion.State != ConnectionState.Open)
                connetion.Open();
            cmmd.Connection = connetion;
            cmmd.CommandText = cmdText;
            if (trans != null)
                cmmd.Transaction = trans;
            cmmd.CommandType = CommandType.Text; //cmdType;
            if (cmdParms != null)
            {
                foreach (SqlParameter parameter in cmdParms)
                {
                    if ((parameter.Direction == ParameterDirection.InputOutput ||
                         parameter.Direction == ParameterDirection.Input) &&
                        (parameter.Value == null))
                    {
                        parameter.Value = DBNull.Value;
                    }
                    cmmd.Parameters.Add(parameter);
                }
            }
        }

        #endregion

        #region 存储过程操作

        /// <summary>
        /// 执行存储过程，返回SqlDataReader ( 注意：调用该方法后，一定要对SqlDataReader进行Close )
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <returns>SqlDataReader</returns>
        public SqlDataReader RunProcedure(string storedProcName, IDataParameter[] parameters)
        {
            OpenDbConnection();
            SqlDataReader returnReader;
            cmd = BuildQueryCommand(conn, storedProcName, parameters);
            cmd.CommandType = CommandType.StoredProcedure;
            returnReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
            return returnReader;
        }


        /// <summary>
        /// 执行存储过程
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <param name="tableName">DataSet结果中的表名</param>
        /// <returns>DataSet</returns>
        public DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName)
        {
            OpenDbConnection();
            DataSet dataSet = new DataSet();
            SqlDataAdapter sqlDA = new SqlDataAdapter();
            sqlDA.SelectCommand = BuildQueryCommand(conn, storedProcName, parameters);
            sqlDA.Fill(dataSet, tableName);
            CloseDbConnection(sqlDA.SelectCommand);
            return dataSet;
        }

        public DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName,
                                           int Times)
        {
            OpenDbConnection();
            DataSet dataSet = new DataSet();
            SqlDataAdapter sqlDA = new SqlDataAdapter();
            sqlDA.SelectCommand = BuildQueryCommand(conn, storedProcName, parameters);
            sqlDA.SelectCommand.CommandTimeout = Times;
            sqlDA.Fill(dataSet, tableName);
            CloseDbConnection(sqlDA.SelectCommand);
            return dataSet;
        }


        /// <summary>
        /// 构建 SqlCommand 对象(用来返回一个结果集，而不是一个整数值)
        /// </summary>
        /// <param name="connection">数据库连接</param>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <returns>SqlCommand</returns>
        private static SqlCommand BuildQueryCommand(SqlConnection connection, string storedProcName,
                                                    IDataParameter[] parameters)
        {
            SqlCommand command = new SqlCommand(storedProcName, connection);
            command.CommandType = CommandType.StoredProcedure;
            foreach (SqlParameter parameter in parameters)
            {
                if (parameter != null)
                {
                    // 检查未分配值的输出参数,将其分配以DBNull.Value.
                    if ((parameter.Direction == ParameterDirection.InputOutput ||
                         parameter.Direction == ParameterDirection.Input) &&
                        (parameter.Value == null))
                    {
                        parameter.Value = DBNull.Value;
                    }
                    command.Parameters.Add(parameter);
                }
            }

            return command;
        }

        /// <summary>
        /// 执行存储过程，返回影响的行数		
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <param name="rowsAffected">影响的行数</param>
        /// <returns></returns>
        public int RunProcedure(string storedProcName, IDataParameter[] parameters, out int rowsAffected)
        {
            OpenDbConnection();
            int result;
            cmd = BuildIntCommand(conn, storedProcName, parameters);
            rowsAffected = cmd.ExecuteNonQuery();
            result = (int) cmd.Parameters["ReturnValue"].Value;
            //Connection.Close();
            CloseDbConnection(cmd);
            return result;
        }

        /// <summary>
        /// 创建 SqlCommand 对象实例(用来返回一个整数值)	
        /// </summary>
        /// <param name="connection"></param>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <returns>SqlCommand 对象实例</returns>
        private static SqlCommand BuildIntCommand(SqlConnection connection, string storedProcName,
                                                  IDataParameter[] parameters)
        {
            SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters);
            command.Parameters.Add(new SqlParameter("ReturnValue",
                                                    SqlDbType.Int, 4, ParameterDirection.ReturnValue,
                                                    false, 0, 0, string.Empty, DataRowVersion.Default, null));
            return command;
        }

        #endregion
    }

    #region 数据成员

    public class ListSql
    {
        public string SqlString;
        public List<Parameter> ListParameter;
    }

    public class Parameter
    {
        public Parameter(string name, object value)
        {
            _Name = name;
            _Value = value;
        }

        private string _Name;
        private object _Value;


        public string Name
        {
            get { return _Name; }
            set { _Name = value; }
        }

        public object Value
        {
            get { return _Value; }
            set { _Value = value; }
        }
    }

    #endregion
}